package com.chujian.framework.util;

import cn.hutool.core.collection.CollUtil;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 脱敏工具类
 */
public class DesensitizeUs {

    /**
     * 用户名脱敏
     *
     * @param userName
     * @return
     */
    public static String desensitizeUserName(String userName) {
        if (StringUtils.isEmpty(userName)) return null;
        String first = userName.substring(0, 1);
        int xinLen = userName.length() - 1;
        return first + creXinStr(xinLen);
    }

    /**
     * 身份证脱敏
     *
     * @param idCard
     * @return
     */
    public static String desensitizeIdCard(String idCard) {
        if (StringUtils.isEmpty(idCard)) return null;
        return middleDesensitize(idCard, 3, 2);
    }

    /**
     * 手机号脱敏
     *
     * @param mobile
     * @return
     */
    public static String desensitizeMobile(String mobile) {
        if (StringUtils.isEmpty(mobile)) return null;
        return middleDesensitize(mobile, 3, 2);
    }


    /**
     * 生日脱敏
     *
     * @param birth
     * @return
     */
    public static String desensitizeBirth(LocalDateTime birth) {
        if (null == birth) return null;
        String day = DateUs.formatDay(birth);
        day = day.replaceAll("-", ".");
        return middleDesensitize(day, 2, 1);
    }

    /**
     * 单位脱敏
     *
     * @param compName
     * @return
     */
    public static String desensitizeCompName(String compName) {
        if (StringUtils.isEmpty(compName)) return null;
        return middleDesensitize(compName, 2, 2);
    }

    /**
     * 中间部分脱敏
     *
     * @param str
     * @param firstLen
     * @param endLen
     * @return
     */
    public static String middleDesensitize(String str, int firstLen, int endLen) {
        int len = str.length();
        String first = str.substring(0, firstLen);
        String end = StringUtils.substring(str, -endLen);
        int xinLen = len - firstLen - endLen;
        return first + creXinStr(xinLen) + end;
    }

    public static String creXinStr(int len) {
        if (len <= 0) return "";

        String[] xs = new String[len];
        Arrays.fill(xs, "*");
        return CollUtil.join(Arrays.asList(xs), "");
    }

}
